//
//  SettingViewController.m
//  NaRiLSVMT
//
//  Created by jmsre on 14-8-10.
//  Copyright (c) 2014年 helloyouth.org. All rights reserved.
//
#import "SettingViewController.h"
#import "MBProgressController.h"
#import "FileManager.h"
#import "TestTCPConnect.h"
#import "NRLSVMTViewController.h"
#import "NetWorkRequestTest.h"
#import "UIViewController+MJPopupViewController.h"
extern  NSTimeInterval  oldCurrentTime;
BOOL    shutDownSetup = NO;
@interface SettingViewController ()
@end
@implementation SettingViewController
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    /**************读本地设置缓存***************/
    if(YES == [dSetupInfofm fileExistsAtPath:dSetupInfopath])
    {
        NSData *data = [NSData dataWithContentsOfFile:dSetupInfopath];
        NSMutableDictionary *dicSetupInfo = [NSMutableDictionary dictionaryWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:data]];
        self.dataSeviceAddr.text = [dicSetupInfo objectForKey:@"dataSeviceAddr"];
        self.pushServerIP.text = [dicSetupInfo objectForKey:@"pushServerIP"];
        self.pushSevicePORT.text = [dicSetupInfo objectForKey:@"pushSevicePORT"];
    }
    /***********************************************************/
    self.topInSettingView.layer.borderWidth = 0.5;
    self.topInSettingView.layer.cornerRadius = 10.0;
    self.topInSettingView.layer.borderColor = [UIColor grayColor].CGColor;
    self.topInSettingView.clipsToBounds = YES;
    self.mainInSettingView.layer.borderWidth = 0.5;
    self.mainInSettingView.layer.cornerRadius = 10.0;
    self.mainInSettingView.layer.borderColor = [UIColor grayColor].CGColor;
    self.mainInSettingView.clipsToBounds = YES;
    //响应键盘通知:
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
   // dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       // sleep(1);
        if(firstLoginSetupUI == 2)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"连接失败!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
   // });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)testconnectAction:(id)sender {
    //测试Http
    //NetWorkRequestTest  *networkRequest = [[NetWorkRequestTest alloc] init];
    [NetWorkRequestTest networkTestConnected];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.dataSeviceAddr.text,@"dataSeviceAddr",self.pushServerIP.text,@"pushServerIP",self.pushSevicePORT.text,@"pushSevicePORT", nil];
    TestTCPConnect *testTcp = [TestTCPConnect sharedInstance];
    
    [testTcp initNetworkCommunication:dic];//测试连接
    
    kBaseUrl = self.dataSeviceAddr.text;
    isTesthttp = YES;
    
}

- (IBAction)connectAction:(id)sender {
    
    if([self.dataSeviceAddr.text isEqualToString:@""])
    {
        [[MBProgressController sharedInstance] showTipsOnlyText:@"数据服务地址为空"
                                                       AndDelay:1.5];
        [[MBProgressController sharedInstance] hide];
        return;
    }
    
    if([self.pushServerIP.text isEqualToString:@""])
    {
        [[MBProgressController sharedInstance] showTipsOnlyText:@"推送服务器IP为空"
                                                       AndDelay:1.5];
        [[MBProgressController sharedInstance] hide];
        return;
    }
    if([self.pushSevicePORT.text isEqualToString:@""])
    {
        [[MBProgressController sharedInstance] showTipsOnlyText:@"推送服务端口为空"
                                                       AndDelay:1.5];
        [[MBProgressController sharedInstance] hide];
        return;
    }
    
    if([dSetupInfofm fileExistsAtPath:dSetupInfopath] == YES)
    {
        [dSetupInfofm removeItemAtPath:dSetupInfopath error:nil];
    }
    /********写本地设置信息***********/
    if([dSetupInfofm fileExistsAtPath:dSetupInfopath] == NO)
    {
        
        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:self.dataSeviceAddr.text,@"dataSeviceAddr",self.pushServerIP.text,@"pushServerIP",self.pushSevicePORT.text,@"pushSevicePORT", nil];
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:params];
        if([dSetupInfofm createFileAtPath:dSetupInfopath contents:data attributes:nil] == NO)
        {
            NSLog(@"create buffer file failure!");
        }

        kBaseUrl = self.dataSeviceAddr.text;
    }
    [NetWorkRequestTest networkTestConnected];
    
    TestTCPConnect *testTcp = [TestTCPConnect sharedInstance];
    [testTcp close];
    TcpClient *tcp = [TcpClient sharedInstance];
    [tcp.asyncSocket disconnect];
    tcp.asyncSocket = nil;
    [tcp setDelegate_ITcpClient:self];
    //[];
//    if(!tcp.asyncSocket.isConnected)
//    {
        NSString *HOST = self.pushServerIP.text;
        NSString *port = self.pushSevicePORT.text;
        [tcp openTcpConnection:HOST port:[port intValue]];
   // }
    /*************************************/
    //校验TCP建立成功
    /*************************************/
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(1);
        if(tcp.asyncSocket.isConnected)
        {
            [[MBProgressController sharedInstance] showTipsOnlyText:@"TCP连接成功"
                                                           AndDelay:1.5];
            [[MBProgressController sharedInstance] hide];
            
            /*********连接成功后，发心跳包**********/
            NSString *requestStr = [NSString stringWithFormat:@"{\"messageData\":\"%@\",\"messageType\":%d}",@"",6];
            [tcp sendTestPacketData:requestStr];
            
            if(firstLoginSetupUI == 1 || firstLoginSetupUI == 2)
            {
                firstLoginSetupUI = 0;
                NRLSVMTViewController   *loginViewController = [[NRLSVMTViewController alloc] initWithNibName:@"NRLSVMTViewController" bundle:nil];
                [loginViewController deviceisRegister:1];
                [loginViewController testUuidlaw];
                [self presentViewController:loginViewController animated:NO completion:nil];
            }
            else{
            if (self.delegate && [self.delegate respondsToSelector:@selector(backButtonClicked:)])
            {
                self.isLogin = NO;
                [self.delegate backButtonClicked:self];
            }
            }
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"连接失败!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
    });

}
- (IBAction)shutdownSetupAction:(id)sender {
//    if(self.isLogin){
//        [self dismissViewControllerAnimated:NO completion:nil];
//    }
//    else{
    if (self.delegate && [self.delegate respondsToSelector:@selector(backButtonClicked:)]) {
        shutDownSetup = YES;
        [self.delegate backButtonClicked:self];
    }
   //}
}


//响应键盘通知:
- (void)keyboardShow:(NSNotification *)note {
    
    if(self.topInSettingView.frame.origin.y <= 50)
    {
        return;
    }
    
    [self.topInSettingView setFrame:CGRectMake(self.topInSettingView.frame.origin.x, self.topInSettingView.frame.origin.y-150, self.topInSettingView.frame.size.width, self.topInSettingView.frame.size.height)];
    [self.mainInSettingView setFrame:CGRectMake(self.mainInSettingView.frame.origin.x, self.mainInSettingView.frame.origin.y-150, self.mainInSettingView.frame.size.width, self.mainInSettingView.frame.size.height)];
}

- (void)keyboardHide:(NSNotification *)note {
    
    if(self.topInSettingView.frame.origin.y >= 200)
    {
        return;
    }
    
    [self.topInSettingView setFrame:CGRectMake(self.topInSettingView.frame.origin.x, self.topInSettingView.frame.origin.y+150, self.topInSettingView.frame.size.width, self.topInSettingView.frame.size.height)];
    [self.mainInSettingView setFrame:CGRectMake(self.mainInSettingView.frame.origin.x, self.mainInSettingView.frame.origin.y+150, self.mainInSettingView.frame.size.width, self.mainInSettingView.frame.size.height)];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.dataSeviceAddr resignFirstResponder];
    [self.pushServerIP resignFirstResponder];
    [self.pushSevicePORT resignFirstResponder];
    [self.imagerSevicePORT resignFirstResponder];
}
#pragma mark -
#pragma mark ITcpClient

/**发送到服务器端的数据*/
-(void)OnSendDataSuccess:(NSString*)sendedTxt;
{
    //self.tfRecived.text = [NSString stringWithFormat:@"%@\r\nsended-->:%@\r\n",self.tfRecived.text,sendedTxt];
}

/**收到服务器端发送的数据*/
-(void)OnReciveData:(NSString*)recivedTxt;
{
    //self.tfRecived.text = [NSString stringWithFormat:@"%@\r\n-->recived:%@\r\n",self.tfRecived.text,recivedTxt];
    
    /*****************这里做信号灯的判断和断网提示**********************/
    NSDateFormatter *dateFormat =[[NSDateFormatter alloc]init];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CH"]];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeInterval  currentTime = [[NSDate date] timeIntervalSince1970];
    
    if(0 != oldCurrentTime)
    {
        if(currentTime - oldCurrentTime > 20 && currentTime - oldCurrentTime<60)
        {
            isHaveDisconnect = YES;
            PostNoticeObserver(@"NetworkSignalNotice", @(1));
        }
        else if(currentTime - oldCurrentTime > 60)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"服务端网络出错!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alert.delegate = self;//断掉后，重连
            [alert show];
            isHaveDisconnect = YES;
            PostNoticeObserver(@"NetworkSignalNotice", @(1));
            //在这里把TCP 完全断掉
        }
        else
        {
            if(isHaveDisconnect == YES)
            {
                PostNoticeObserver(@"NetworkSignalNotice", @(0));
            }
        }
    }
    oldCurrentTime = currentTime;
    /**************************************************************/
    
    NSInteger   lastLengh = recivedTxt.length;
    NSRange subIndex = [recivedTxt rangeOfString:@"\r\n"];
    while(!(subIndex.location == NSNotFound) && (lastLengh>0))
    {
        NSString *subStr = [recivedTxt substringWithRange:NSMakeRange(0, subIndex.location)];
        //NSLog(@"%@ 根据服务端反馈的命令，来做出响应的处理",subStr);
        
        NSRange boolSendNotice;
        boolSendNotice = [subStr rangeOfString:@"GetEvents"];
        if(!(boolSendNotice.location == NSNotFound))
        {
            PostNoticeObserver(NoticeKey_TcpGetEvents, subStr);
        }
        
        //播放器关掉  刷新数据
        boolSendNotice = [subStr rangeOfString:@"DeviceGetScreenInfo"];
        
        if(!(boolSendNotice.location == NSNotFound))
        {
            PostNoticeObserver(NoticeKey_TcpDeviceGetScreen, subStr);
        }
        
        boolSendNotice = [subStr rangeOfString:@"UpdateClient"];
        
        if(!(boolSendNotice.location == NSNotFound))
        {
            PostNoticeObserver(NoticeKey_TcpUpateClient, subStr);
        }
        
        //        boolSendNotice = [subStr rangeOfString:@"DeviceGetScreenInfo"];
        //
        //        if(!(boolSendNotice.location == NSNotFound))
        //        {
        //            PostNoticeObserver(@"NoticeKey_TcpGetEvents_String", subStr);
        //        }
        ////////////////////////////////////////////////////////////////////
        
        lastLengh -= (subIndex.location+2);
        if(lastLengh > 0)
        {
            subIndex = [[recivedTxt substringWithRange:NSMakeRange(subIndex.location+2, lastLengh)] rangeOfString:@"\r\n"];
        }
    }

    
    NSLog(@"%@",recivedTxt);
}

/**socket连接出现错误*/
-(void)OnConnectionError:(NSError *)err;
{
    //self.tfRecived.text = [NSString stringWithFormat:@"%@\r\n\r\n**** network error! ****\r\n",self.tfRecived.text];
//    [[MBProgressController sharedInstance] showTipsOnlyText:@"**** 网络错误! ****"
//                                                   AndDelay:1.5];
//    [[MBProgressController sharedInstance] hide];
    return;
}

#pragma mark-
#pragma mark- UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    TcpClient *tcp = [TcpClient sharedInstance];
    [tcp setDelegate_ITcpClient:self];
    if(!tcp.asyncSocket.isConnected)
    {
        NSString *HOST = self.pushServerIP.text;
        NSString *port = self.pushSevicePORT.text;
        [tcp openTcpConnection:HOST port:[port intValue]];
    }
    /*************************************/
    //校验TCP建立成功
    /*************************************/
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(1);
        if(tcp.asyncSocket.isConnected)
        {
            /*********连接成功后，发心跳包**********/
            NSString *requestStr = [NSString stringWithFormat:@"{\"messageData\":\"%@\",\"messageType\":%d}",@"",6];
            [tcp sendTestPacketData:requestStr];

        }
        else
        {
            [[MBProgressController sharedInstance] showTipsOnlyText:@"请进行测试连接确认连接成功"
                                                           AndDelay:1.5];
            [[MBProgressController sharedInstance] hide];
            return;
        }
    });
}



@end
